package com.xujiang.myblog.network.okhttp;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import com.xujiang.myblog.util.L;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by xujiang on 2017/4/13.
 */

public class MOkhttp {
    public static final String TAG = MOkhttp.class.getSimpleName();

    private static OkHttpClient client = new OkHttpClient();


    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    /**
    * get请求
    * */
    private  static  final  int GET=1;
    /**
    * post请求
    * */
    private  static  final  int POST=2;


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case GET:
                    //获取数据
                    //tv_result.setText((String)msg.obj);
                    break;
                case POST:
                    //获取数据
                    //tv_result.setText((String)msg.obj);
                    break;


            }
        }
    };

    /**
     * get请求网络数据
     * */
    public static void getDataFromGet(final String url){
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    String result = get(url);
                    L.i(TAG,result);
//                    Message msg = Message.obtain();
//                    msg.what = GET;
//                    msg.obj = result;
//                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
      * 网络连接http get 请求
      *okhttp3
      * */
    private static String get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();   //绑定创建

        Response response = client.newCall(request).execute();  //execute执行线程
        if (response.isSuccessful()) {
            return response.body().string();
        }
        else
        {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
    *post请求
    *需要在线程中请求
    * */
    public static String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();

        if (response.isSuccessful()) {
            return response.body().string();
        }
        else
        {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * post请求
     * 键值对的形式
     * */
    public static String post2(String url) throws IOException {

        RequestBody body = new FormBody.Builder()
                .add("one", "one")
                .add("two", "two")
                .add("three", "three")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();

        if (response.isSuccessful()) {
            return response.body().string();
        }
        else
        {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * okhttp 上传图片
     * */
    //文档demo
//    MultipartBody body = new MultipartBody.Builder("AaBo3x")
//            .setType(MultipartBody.FORM)
//            .addFormDataPart("files",null,new MultipartBody.Builder("BbCo4y").addPart(
//                    Headers.("Content-Disposition", "form-data; filename=\"img.png\""),
//            RequestBody.create(MediaType.parse("image/png"), new File(path)))
//            .build()).build();

    //关于这个文件上传，在服务器端没有实现，查了很多资料，不知道怎么接受到数据，暂时放弃，以后再站
    public static void upFile(String url, Context context){
        /* 第一个要上传的file */
        File file1 = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/testfile/test.jpg");
        RequestBody fileBody1 = RequestBody.create(MediaType.parse("application/octet-stream"),file1);
        String file1Name = "test";
        /* 第二个要上传的文件,这里偷懒了,和file1用的一个图片 */
        File file2 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/a.jpg");
        RequestBody fileBody2 = RequestBody.create(MediaType.parse("application/octet-stream") , file2);
        String file2Name = "a";
        /* form的分割线,自己定义 */
        String boundary = "xx--------------------------------------------------------------xx";
        MultipartBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                /* 上传一个普通的String参数 , key 叫 "p" */
        //.addFormDataPart("p","test")
        /* 底下是上传了两个文件 */
                .addFormDataPart("file",file1Name,fileBody1)
                .addFormDataPart("file",file2Name,fileBody2)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String bodyStr = response.body().string();
                final boolean ok = response.isSuccessful();
                //context.runOnUiThread()
            }
        });

    }

    /**
     * 上面方法上传后台没有找到方法接收数据
     * 下面是新的方法实验
     * 经test 下面的方法测试成功，可以获取数据
     * 多文件上传也获得成功
     * */
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    public static void upFile2(String url, List<File> files, Map<String, String> maps,String pic_key){

        MultipartBody.Builder builder=  new MultipartBody.Builder().setType(MultipartBody.FORM);
//        if(maps==null) {
//            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"file\";filename=\"file.jpg\""), RequestBody.create(MediaType.parse("image/png"), file)
//            ).build();
//        } else{
            for (String key : maps.keySet()) {
                L.i(TAG,key+":"+maps.get(key));
                builder.addFormDataPart(key, maps.get(key));
            }
//        }
        //单文件
        //builder.addPart( Headers.of("Content-Disposition", "form-data; name=\"file\";filename=\"file.jpg\""), RequestBody.create(MediaType.parse("image/png"),file)
        //多文件
        //遍历paths中所有图片绝对路径到builder，并约定key如“upload”作为后台接受多张图片的key
        if (files != null){
            for (File file : files) {
                builder.addFormDataPart(pic_key, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
            }
        }
        RequestBody body=builder.build();
        Request request = new Request.Builder().url(url).post(body).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                L.i(TAG,"failed");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                L.i(TAG,"success");
            }
        });


    }







}
